Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    showPassword: false,
    showConfirmPassword: false,
    loading: false
  },

  // 处理输入
  handleInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [field]: e.detail.value
    });
  },

  // 切换密码显示状态
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  // 切换确认密码显示状态
  toggleConfirmPassword() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },

  // 注册
  async register(e) {
    const { username, password, confirmPassword } = e.detail.value;
    
    // 表单验证
    if (!username || !password || !confirmPassword) {
      wx.showToast({
        title: '请完善所有信息',
        icon: 'none'
      });
      return;
    }
    
    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }
    
    if (password.length < 6) {
      wx.showToast({
        title: '密码长度不能少于6位',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    try {
      // 获取数据库引用
      const db = wx.cloud.database();
      
      // 检查用户名是否已存在
      const userCheck = await db.collection('users')
        .where({
          username: username
        })
        .get();
      
      if (userCheck.data.length > 0) {
        wx.showToast({
          title: '用户名已存在',
          icon: 'none'
        });
        this.setData({ loading: false });
        return;
      }
      
      // 创建新用户
      const result = await db.collection('users').add({
        data: {
          username: username,
          password: password, // 实际应用中应该加密存储
          createdAt: new Date()
        }
      });
      
      if (result._id) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
        
        // 延迟跳转登录页
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }, 1500);
      }
    } catch (err) {
      console.error('注册失败：', err);
      wx.showToast({
        title: '注册失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  }
})
